package handlers

import (
	"fmt"
	"github.com/gorilla/websocket"
	"github.com/vmihailenco/msgpack/v5"
	"gogogo-server/gameserver/game"
	"gogogo-server/gameserver/model"
	"gogogo-server/gameserver/protocols"
	"gogogo-server/gameserver/service"
	"log"
)

type LoginHandler struct {
	// 可以添加所需的属性和依赖项
}

var playerConns = make(map[*websocket.Conn]*game.PlayerConn)

func NewLoginHandler() *LoginHandler {
	return &LoginHandler{
		// 初始化
	}
}

func (h *LoginHandler) HandleMessage(conn *websocket.Conn, msg *protocols.Message) error {
	switch msg.Event {
	case "login":
		log.Println(msg.Event)
		return h.handleLogin(conn, msg.Data)
	// 更多消息类型...
	default:
		return fmt.Errorf("unsupported message type: %s", msg.Event)
	}
}

func (h *LoginHandler) handleLogin(conn *websocket.Conn, data []byte) error {
	var loginData protocols.LoginRequest
	err := msgpack.Unmarshal(data, &loginData)
	// 处理创建房间的逻辑
	if err != nil {
		return fmt.Errorf("failed to unmarshal login data: %v", err)
	}

	playerService := service.DataService.GetPlayerService()
	player, err := playerService.GetByName(loginData.Name)
	if err != nil {
		// 处理错误
	}
	if player == nil {
		initPlayer := &model.Player{
			ID:       1000,
			Diamonds: 1000,
			Coins:    1000,
			Level:    1,
			Name:     loginData.Name,
		}
		err = playerService.Create(initPlayer)
		if err != nil {
			return fmt.Errorf("cannot create")
		}
	}

	playerConn := &game.PlayerConn{Player: player, Conn: conn}
	playerConns[conn] = playerConn
	// 在实际应用中，您可以将玩家添加到房间，执行加入房间的逻辑
	// 这里仅向客户端发送成功加入房间的消息
	data, err = msgpack.Marshal(protocols.LoginResponse{Name: loginData.Name, Player: *player})
	if err != nil {
		log.Println("MessagePack Marshal Error:", err)
		return err
	}
	successMsg := protocols.Message{
		Event: "login",
		Data:  data,
	}
	err = service.SendMsg(conn, successMsg)
	if err != nil {
		return err
	}
	return nil
}
